﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;

namespace RStein.Posterous.API
{
    internal class BitLyService : IBitLyService
    {

        #region constructors

        public BitLyService(IPosterousApplication application)
        {
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }

            Application = application;
        }

        #endregion constructors

        #region methods
        protected void OnSinglePostLoaded(EventArgsValue<ISinglePostInfo> e)
        {
            EventHandler<EventArgsValue<ISinglePostInfo>> handler = SinglePostLoaded;
            if (handler != null)
            {
                Thread.CurrentThread.GetCurrentSynchronizationContext().Post(o => handler(this, e), null);
            }
        }
        #endregion methods
        #region Implementation of IBitLyService

        public ISinglePostInfo GetSinglePost(string bitLySuffix)
        {
            if (String.IsNullOrEmpty(bitLySuffix))
            {
                throw new ArgumentNullException(bitLySuffix);
            }

            var builder = SimpleWebFactory.Instance.Create<IPosterousRequestBuilder>(); ;
            builder.StartBuildWebRequest(GlobalConstants.URL_BITLY_GET_POST);
            builder.BuildFormData(GlobalConstants.BIT_LY_POST_ID, bitLySuffix);
            
            ISinglePostInfo post = processResponse(builder);
            
            Debug.Assert(post != null);
            
            OnSinglePostLoaded(new EventArgsValue<ISinglePostInfo>(post, null));            
            
            return post;            
        }

        private ISinglePostInfo processResponse(IPosterousRequestBuilder builder)
        {
            WebResponse response = builder.GetResponse();
            var parser = new SimplePostResponseParser();
            var responseBuilder = new PosterousResponseBuilder();
            var retPost = responseBuilder.ParseResponse(response, parser.GetResults).Single();
            return retPost;
        }

        public void GetSinglePostAsync(string bitLySuffix)
        {
            Action<Exception> exchandler = e =>
            {
                new PosterousException(GlobalConstants.ASYNC_EXCEPTION_TEXT, e);
                OnSinglePostLoaded(new EventArgsValue<ISinglePostInfo>(null, e));
            };

            AsyncHelper.RunDelegateAsync((Func<String, ISinglePostInfo>) GetSinglePost, exchandler, null, bitLySuffix);             
        }

        public event EventHandler<EventArgsValue<ISinglePostInfo>> SinglePostLoaded;
        
        #endregion

        #region Implementation of IApplicationHolder

        public IPosterousApplication Application
        {
            get; 
            set;
        }

        #endregion
    }
}